package com.zm.zmgz.service;

import com.zm.zmgz.dao.ReportManagementBeanMapper;
import com.zm.zmgz.pojo.ProjectProfitBatchOptionBean;
import com.zm.zmgz.pojo.ReportManagementBean;
import com.zm.zmgz.pojo.ReportManagementBeanExample;
import com.zm.zmgz.utils.DateUtils;
import com.zm.zmgz.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: cjw
 * @Date: 2020/06/15/9:17
 * @Description: 报表管理业务层
 */
@Service
public class ReportManagementService {

    @Autowired
    ReportManagementBeanMapper mapper; // 报表管理dao层接口

    /***
     * @Description: 添加一条报表记录
     * 添加前判断是否已经存在该文件(根据批次和文件名来判断)
     *  如果存在就删除文件,删除记录
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-06-15 09:18:39
     */
    @Transactional
    public Integer add(String url, String batch, HttpServletRequest request) {
        ReportManagementBean bean = new ReportManagementBean();
        Date date = DateUtils.getDateByString(batch, "yyyy年MM月");
        String fileName = url;
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 添加前判断是否已经存在该文件(根据批次和文件名来判断)
        Boolean b = isExist(fileName, batch);
        // 如果存在就删除文件,删除记录
        if (b) {
            // 文件上传失败不需要退出
//            boolean b1 = FileUtils.deleteFileByUrlAndRequest(request,url);
//            if (!b1) {
//                System.err.println(url + "  文件删除失败!");
//            }
            // 记录删除失败就会退出
            Integer integer = deleteByBatchAndFileName(batch, fileName);
            if (integer == 0) {
                System.err.println(url + "记录删除失败!");
                return null;
            }
        }
        bean.setBatch(batch);
        bean.setBatchdate(date);
        bean.setFilename(fileName);
        bean.setFiletype(fileType);
        int i = mapper.insert(bean);
        return i;
    }

    /***
     * @Description: 通过batch和文件名来删除记录
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-06-15 09:44:30
     */
    public Integer deleteByBatchAndFileName(String batch, String fileName) {
        ReportManagementBeanExample example = new ReportManagementBeanExample();
        ReportManagementBeanExample.Criteria criteria = example.createCriteria();
        criteria.andBatchEqualTo(batch).andFilenameEqualTo(fileName);
        return mapper.deleteByExample(example);

    }

    /***
     * @Description: 根据批次和文件名来判断文件是否存在
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-06-15 09:36:45
     */
    public Boolean isExist(String fileName, String batch) {
        ReportManagementBeanExample example = new ReportManagementBeanExample();
        ReportManagementBeanExample.Criteria criteria = example.createCriteria();
        criteria.andBatchEqualTo(batch).andFilenameEqualTo(fileName);
        List<ReportManagementBean> list = mapper.selectByExample(example);
        if (Objects.isNull(list) || list.size() == 0)
            return false;
        else
            return true;
    }

    /***
     * @Description: 获取全部数据并按要求排序
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-22 03:00:35
     */
    private List<ReportManagementBean> getAllAndOrder(String order) {
        ReportManagementBeanExample example = new ReportManagementBeanExample();
        example.setOrderByClause(order);
        List<ReportManagementBean> list = mapper.selectByExample(example);
        return list;
    }

    /***
     * @Description: 获取批次选择数据
     * - 获取全部记录(排序:填写日期升序,数额降序;"settlementDate ASC,amount DESC")
     * - 遍历全部记录，创建数据对象集合
     *   - 获取时间，提取年，年级中是否存在该年
     *     - 有则提取月，判断月级中是否存在该月
     *       - 有则舍弃（看你是否要日级）
     *       - 无则创建该月级
     *     - 无则创建该年级
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-21 21:36:15
     */
    public List<ProjectProfitBatchOptionBean> getBatchOptions() {
        // 获取全部记录(排序:批次升序,文件类型降序;batchDate ASC, fileType DESC)
        String order = "batchDate ASC, fileType DESC";
        List<ReportManagementBean> list = getAllAndOrder(order);
        if (Objects.isNull(list) || list.size() == 0)
            return null;
        // 遍历全部记录，创建数据对象集合,进行解析
        List<ProjectProfitBatchOptionBean> list1 = new ArrayList<>();
        for (ReportManagementBean reportManagementBean : list) {
            Date date = reportManagementBean.getBatchdate();
            String year = DateUtils.getDateString(date, "YYYY年");
            String month = DateUtils.getDateString(date, "MM月");
            // 搜索是否存在该年;如果不存在就添加该年该月
            int i = 0;
            for (ProjectProfitBatchOptionBean bean : list1) {
                // 该年存在
                if (bean.getValue().equals(year)) {
                    // 搜索是否存在该月
                    List<ProjectProfitBatchOptionBean> list2 = bean.getChildren();
                    int j = 0;
                    // 遍历该年是否存在该月
                    for (ProjectProfitBatchOptionBean optionBean : list2) {
                        if (optionBean.getLabel().equals(month)) {
                            j++;
                            break;
                        }
                    }
                    // 该年存在,但该月不存在,添加月
                    if (j == 0) {
                        ProjectProfitBatchOptionBean optionBean1 = new ProjectProfitBatchOptionBean();
                        optionBean1.setValue(year + month);
                        optionBean1.setLabel(month);
                        bean.getChildren().add(optionBean1);
                    }
                    i++;
                    break;
                }
            }
            // 该年不存在
            if (i == 0) {
                ProjectProfitBatchOptionBean optionBean = new ProjectProfitBatchOptionBean();
                optionBean.setLabel(year);
                optionBean.setValue(year);
                optionBean.setChildren(new ArrayList<>());
                ProjectProfitBatchOptionBean optionBean1 = new ProjectProfitBatchOptionBean();
                optionBean1.setValue(year + month);
                optionBean1.setLabel(month);
                optionBean.getChildren().add(optionBean1);
                list1.add(optionBean);
            }

        }
        return list1;
    }



    /***
     * @Description: 根据传入日期, 获取日期内批次数据
     * 排序:文件类型降序
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 12:17:34
     */
    public List<Map<String,String>> getBatchByDate(Date date) {
        Date monthStart = DateUtils.getMonthStart(date);
        Date monthEnd = DateUtils.getMonthEnd(date);
        ReportManagementBeanExample example = new ReportManagementBeanExample();
        ReportManagementBeanExample.Criteria criteria = example.createCriteria();
        criteria.andBatchdateBetween(monthStart, monthEnd);
        example.setOrderByClause("fileType desc");
        List<ReportManagementBean> list = mapper.selectByExample(example);
        if (Objects.isNull(list) || list.size() == 0)
            return null;
        List<Map<String,String>> list1 = new ArrayList<>();
        for (ReportManagementBean bean : list) {
            Map<String,String> map = new HashMap<>();
            String filename = bean.getFilename();
            String filename2 = FileUtils.getFileNameByUrl(filename);
            map.put("url",filename);
            map.put("fileName",filename2);
            list1.add(map);
        }
        return list1;

    }
}
